#!/usr/bin/env python2.5
#coding: utf8

#Author: Gang Li
#Date: 2010-04-10 18:20

import sys,os
import re
import cgi

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class MRHTTPRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        """Handle a single HTTP request"""
        print dir(self), dir(self.headers)

        p = re.search(r"/(.*\.py)$",self.path)
        if p:
            name = p.group(1)

            print "file: %s "%(self.res_path+name)
            self.send_response(200, "OK")
            self.end_headers()

            _f = self.res_path+name
            if os.path.isfile(_f):
                print "load module from web server:", _f
                f = open(_f)
                self.wfile.write(f.read())
                f.close()

    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers.getheader("content-type"))

        form = cgi.FieldStorage (fp = self.rfile,
                               headers = self.headers,
                               environ = {'REQUEST_METHOD' : 'POST'},
                               keep_blank_values = 1,
                               strict_parsing = 1)
        if not form.has_key ("file"):
           self.send_error (403, "No upload provided")
           return

        upfile = form["file"]

#        if not upfile.file or not upfile.filename:
#           self.send_error (403, "No upload provided")
#           return
#
#        upfilename = upfile.filename

        n = self.res_path+self.path[1:]

        if os.path.exists(n):
           self.send_error (403, "package has already exists")
           return

        self.send_response(200)
        self.end_headers()
        
        dir = os.path.split(n)[0]
        if not os.path.exists(dir):
            os.makedirs(dir)


        f = open(n, 'wb')
        f.write(upfile.file.read())
        f.close()


def start_http_server(HandlerClass = MRHTTPRequestHandler, ServerClass = HTTPServer, port = 2010, protocol="HTTP/1.1"):
    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    HandlerClass.res_path = "./resource/"
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.serve_forever()

if __name__ == "__main__":
    from threading import Thread as _t
    _t(target=start_http_server).start()

    import time
    time.sleep(.2)

    import urllib
    import urllib2
    import MultipartPostHandler

    opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)

    data = {"file":open("c:/httpdownload.txt","rb")}
    r = opener.open("http://localhost:2010/a/t.txt", data)

    print r.code, r.msg